import {IMessage} from "@/components/aw-message/message";

export interface MessageOptions {
    appid?: string,
    cover?: boolean,
    delay?: number,
    icon?: string,
    sound?: 'system' | 'none',
    title: string,
    subTitle?: string,
    when?: Date,
}

export interface Payload {
    __UUID__: string,
    title: string,
    appid: string,
    content: string,
    payload: string
}

/**
 *  推送消息
 * @param msg
 * @param type
 */
export const pushMsg = (msg: pushMessage, type?: "success" | "error" | "warning" | "info") => {
    const option: MessageOptions = {
        title: msg.title,
        sound: 'system',
        icon: '/static/app.png',
        cover: false,
        subTitle: msg.subTitle,
        when: new Date(),
    }
    const payload = JSON.stringify(msg)
    // #ifdef APP-PLUS
    plus.push.createMessage(msg.content, payload, option)
    // #endif
    console.log(msg.type)
    if (msg.type === 'chat') {
        return
    }
    IMessage({
        content: msg.content,
        showIcon: true,
        type: type || 'success',
        duration: 5000,
        appDuration: "long"
    })

}
export const setBadge = (num: number) => {
    // #ifdef APP-PLUS
    plus.runtime.setBadgeNumber(num)
    // #endif

}

export const listenPush = () => {
    // #ifdef APP-PLUS

    // @ts-ignore
    plus.push.addEventListener("click", (payload: Payload) => {
        const message: pushMessage = JSON.parse(payload.payload) as pushMessage
        console.log('点击推送消息')
        console.log(payload)
        if (message.messageUrl) {
            console.log('跳转', message.messageUrl)
            uni.navigateTo({
                url: message.messageUrl
            })
        }
    })
    // @ts-ignore
    plus.push.addEventListener("receive", (payload: Payload) => {
        const message: pushMessage = JSON.parse(payload.payload) as pushMessage
        console.log('点击推送消息')
        console.log(payload)
        if (message.messageUrl) {
            console.log('跳转', message.messageUrl)
            uni.navigateTo({
                url: message.messageUrl
            })
        }
    })
    // #endif

}